/*
-------------------------------------------------

	Console.cpp

	Dmitriy Kuzmenko (Dgut)

-------------------------------------------------
*/

#include "Console.h"
#include "File.h"
#include <stdarg.h>

using namespace std;

namespace Autumn
{

Console::Console( void )
{
}

Console::~Console( void )
{
}

const bool Console::Init( void )
{
	stream = gFile.Open( "log.txt", "wt" );
	if( !stream )
		return false;

	return true;
}

void Console::Shutdown( void )
{
	fclose( stream );
}

void Console::Log( const char * text/*, ...*/ )
{
	/*static char buffer[ 1024 ] = { 0 };

	va_list	arg;
	
	va_start( arg, text );
	vsnprintf( buffer, sizeof( buffer ), text, arg );
	va_end( arg );*/

	logs.push_back( /*buffer*/text );
	fputs( /*buffer*/text, stream );
	fputc( '\n', stream );
}

const char * const Console::GetLog( int line ) const
{
	return line < logs.size() ? logs[ logs.size() - line - 1 ].c_str() : 0;
}

void Console::SetVariable( const char * name, const char * value )
{
	variables[ name ] = value;
}

const char * const Console::GetVariable( const char * name ) const
{
	const map< string, string >::const_iterator i = variables.find( name );

	return i == variables.end() ? 0 : i->second.c_str();
}

const float Console::GetVariableFloat( const char * name ) const
{
	const map< string, string >::const_iterator i = variables.find( name );

	return i == variables.end() ? 0.f : atof( i->second.c_str() );
}

void Console::AddCommand( const char * name, Command command )
{
	commands[ name ] = command;
}

void Console::Execute( const char * text )
{
	//static char buffer[ 1024 ] = { 0 };
	char buffer[ 1024 ];

	strncpy( buffer, text, sizeof( buffer ) - 1 );

	char * key = strtok( buffer, " " );

	if( !key )
	{
		Log( "" );
		return;
	}

	static const int MAX_ARGS = 16;
	
	char * argv[ MAX_ARGS ];
	int argc = 0;

	char * arg = strtok( 0, " " );

	while( arg && argc < MAX_ARGS )
	{
		argv[ argc++ ] = arg;
		arg = strtok( 0, " " );
	}

	if( variables.find( key ) != variables.end() )
	{
		if( argc )
			variables[ key ] = argv[ 0 ];
		else
		{
			char buffer[ 1024 ];
			sprintf( buffer, "\"%s\" is \"%s\"", key, variables[ key ] );
			Log( buffer );
		}
		return;
	}

	if( commands.find( key ) != commands.end() )
	{
		commands[ key ]( argc, ( const char * * )argv );
		return;
	}

	Log( "Unknown command \"%s\"" );
}

}	// namespace Autumn